package de.zainodis.triplog.data.persistence;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTableConfig;

import java.sql.SQLException;

import de.zainodis.triplog.data.LocationEntry;
import de.zainodis.triplog.data.share.TriplogContract;

/**
 * Created by fzarrai on 9/9/2014.
 */
public interface ILocationDao extends Dao<LocationEntry, Long> {

    //Table name for LocationEntry.
    public static final String TABLE_NAME = "location";
    //Id column of the Location table
    public static final String COLUMN_ID = "_id";
    //The location setting string is what will be sent to openweathermap as the location query.
    public static final String COLUMN_LOCATION_SETTING = "location_setting";
    // Human readable location string, provided by the API. Because for styling, "Mountain View" is more recognizable than 94043.
    public static final String COLUMN_CITY_NAME = "city_name";
    //In order to uniquely pinpoint the location on the map when we launch the  map intent, we store the latitude and longitude as returned by openweathermap.
    public static final String COLUMN_COORD_LAT = "latitude";
    public static final String COLUMN_COORD_LONG = "longitude";
    public static final String COLUMN_FK_TRIP = "fkTrip";


    /**
     * This method is used by the content provider to insert a new location if it does not already exist.
     * This also handles inserting of related weather data if available.
     *
     * @param context  Activity context required to obtain other relevant dao objects.
     * @param location the trip to create if it does not already exist.
     * @return the database id.
     */
    public long createIfNotExists(Context context, LocationEntry location) throws SQLException;

    /**
     * @return the location belonging to the ongoing trip; null if there is none.
     */
    public LocationEntry getOngoingTripLocation(Context context);

    public class LocationDao extends BaseDaoImpl<LocationEntry, Long> implements ILocationDao {
        private static final String TAG = "LocationDao";

        public LocationDao(ConnectionSource connectionSource) throws SQLException {
            super(connectionSource, LocationEntry.class);
        }

        public LocationDao(ConnectionSource connectionSource, DatabaseTableConfig<LocationEntry> tableConfig)
                throws SQLException {
            super(connectionSource, tableConfig);
        }

        @Override
        public long createIfNotExists(Context context, LocationEntry location) throws SQLException {
            LocationEntry entry = super.createIfNotExists(location);
            if (entry == null) {
                throw new SQLException("Failed to insert location - returned location is null.");
            }

            return entry.getId();
        }

        @Override
        public LocationEntry getOngoingTripLocation(Context context) {
            //Search for a trip using the start date, since there can be only one ongoing trip at a time
            Cursor cursor = context.getContentResolver().query(
                    TriplogContract.CONTENT_URI_TRIP, new String[]{ITripDao.COLUMN_ID}, ITripDao.COLUMN_DATE_END + " = ?",
                    new String[]{""},
                    null);

            long tripId = -1;
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndex(COLUMN_ID);
                tripId = cursor.getLong(columnIndex);
            }

            if (tripId <= 0) {
                Log.w(TAG, "Failed to retrieve ongoing trip location - there is no ongoing trip.");
                return null;

            }
            //Lookup location via trip id
            cursor = context.getContentResolver().query(
                    TriplogContract.CONTENT_URI_LOCATION, null, COLUMN_FK_TRIP + " = ?",
                    new String[]{String.format("\'%s\'"), String.valueOf(tripId)},
                    null);
            if (cursor.moveToFirst()) {
                //We got something, load the data from the cursor
                return new LocationEntry(cursor);
            }
            return null;

        }
    }
}
